<template lang="pug">
  el-row(v-show="config")
    el-col(:span="12")
      el-form(:inline="true" v-show="actions && actions.length" @submit.native.prevent)
            el-form-item
                el-select(v-model="actionItem")
                    el-option(v-for="action in actions" :key="action.label" :label="action.label" :value="action.label")
            el-form-item
                el-button(type="danger" @click="submit") 执行
      span() &nbsp;
    el-col(:span="12" class="pull-right")
        el-button(@click="createOrCloseBtnClick" type="primary") 新建
</template>
<script>
import { mapActions, mapGetters } from "vuex";
import { Message } from "element-ui";

import axios from "../../../plugins/axios";

export default {
  name: "action-bar",
  data() {
    return {
      actions: [],
      actionItem: ""
    };
  },
  props: {
    config: { type: Object }
  },
  computed: {

    checkedRowIds() {
      return this.$store.state.table.checkedRowIds;
    },

    formVisible() {
      return this.$store.state.status.formVisible;
    },

    activedAction() {
      const vm = this;
      return this.actions.find(t => t.label == vm.actionItem);
    }
  },
  methods: {
    createOrCloseBtnClick() {
      this.$store.dispatch("status/showInsert");
    },

    submit() {
      if (this.checkedRowIds.length === 0) {
        Message.warning("请选择数据");
        return;
      }
      const confirmText = this.activedAction.confirmText.trim();
      if (confirmText) {
        const buttons = {
          confirmButtonText: "确定执行",
          cancelButtonText: "取消",
          type: "warning"
        };

        const vm = this;
        this.$confirm(confirmText, "操作确认", buttons)
          .then(() => {
            vm.doSubmit();
          })
          .catch(() => {
            Message.info("操作已取消");
          });
        return;
      }

      this.doSubmit(); // 不需要确认直接进行操作
    },

    doSubmit() {
      const url = this.activedAction.actionUrl;
      const models = this.checkedRowIds;
      const options = { url, method: "post", data: { models } };

      axios(options)
        .then(res => {
          this.$emit("submit-success", res);
          Message.success("执行成功");
        })
        .catch(err => {
          Message.error(err.message);
        });
    }
  },

  created() {
    const actions = this.config.actions;
    this.actions = actions;
    this.actionItem = actions && actions.length ? actions[0].label : "";
  }
};
</script>
<style scoped>
.pull-right {
  text-align: right;
}
</style>
